package com.magnate.software.spring.redis.dao.serializer;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.msgpack.MessagePack;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.IOException;

/**
 * MsgPack序列化工具
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2016/8/30 21:01
 */
public class MsgPackRedisSerializer<T> implements RedisSerializer<T> {

    private Class<T> classType;

    private MessagePack msgPack = new MessagePack();

    private GenericObjectPool<MessagePack> pool;

    public void setPool(GenericObjectPool<MessagePack> pool) {
        this.pool = pool;
    }

    public byte[] serialize(T t) throws SerializationException {
        if (t == null)
            return new byte[0];

        try {
            return msgPack.write(t);
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null)
            return null;

        try {
            T t;
            if (classType != null) {
                t = msgPack.read(bytes, classType);
            } else {
                t = (T) msgPack.read(bytes);
            }

            if (pool != null) {
                pool.returnObject(msgPack);
            }
            return t;
        } catch (IOException e) {
            e.printStackTrace();
            pool.returnObject(msgPack);
            return null;
        }
    }

    public Class<T> getClassType() {
        return classType;
    }

    public void setClassType(Class<T> classType) {
        this.classType = classType;
    }
}
